package com.lee.auth.endpoint.verifier.third;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lee.auth.endpoint.verifier.ThirdVerifier;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonMap;

/**
 * @author Lee HN
 * @date 2020/7/18 19:48
 */
@Service
@AllArgsConstructor
public class WeiBoThirdVerifier implements ThirdVerifier {

    private final ObjectMapper objectMapper;

    private static final String url = "https://api.weibo.com/oauth2/get_token_info";

    @Override
    public boolean verify(String openId, String token) {
        Map<String, Object> params = singletonMap("access_token", token);
        HttpRequest httpRequest = HttpRequest.post(url).form(params).acceptEncoding(UTF_8.name());
        HttpResponse httpResponse = httpRequest.send();
        String body = httpResponse.bodyText();
        JsonNode readNode;
        try {
            readNode = objectMapper.readTree(body);
        } catch (IOException e) { return true; }
        String uid = readNode.path("uid").asText();
        return !Objects.equals(uid, openId);
    }

    @Override
    public int getProvider() {
        return Weibo;
    }

}
